package com.why.controller;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.why.entity.Cop;
import com.why.entity.Result;
import com.why.entity.Search;
import com.why.entity.User;
import com.why.service.ICopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hy-woo
 * @since 2022-06-07
 */
@RestController
@RequestMapping("/cop")
public class CopController {

    @Autowired
    ICopService copService;

    @Autowired
    RedisTemplate redisTemplate;

    @RequestMapping("/upSave")
    public Result upSave(@RequestBody Cop cop){
        boolean b1 = copService.updateById(cop);
        return b1?new Result(200,"","ok"):new Result(909,"","no");
    }

    @RequestMapping("/getCop")
    public Result getCop(int id){
        Cop cop = copService.getById(id);
        return new Result(200,"",cop);
    }

    @RequestMapping("/save")
    public Result save(@RequestBody Cop cop){
        // 校验用户权限
        // 当前登录得用户信息
        Object o = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (!(o instanceof User)){
            return new Result(909,"","匿名用户不逊需提交");
        }
        User loginUser = (User) o;
        if (!"admin".equals(loginUser.getRole())){
            return new Result(908,"","只有管理员才能提交");
        }
        // 防止表单重复提交
        String s = DigestUtils.md5DigestAsHex(JSONUtil.toJsonStr(cop).getBytes(StandardCharsets.UTF_8));
        Boolean b = redisTemplate.opsForValue().setIfAbsent(s, new Date(), 30, TimeUnit.SECONDS);
        if (!b){
            return new Result(910,"","重复提交");
        }
        boolean b1 = copService.saveOrUpdate(cop);
        return b1?new Result(200,"","ok"):new Result(900,"","no");
    }

    @RequestMapping("/delAll")
    public Result delAll(int[] ids){
        for (int id : ids) {
            copService.removeById(id);
        }
        return new Result(200,"ok","删除成功");
    }


}
